package com.example.handler;

import com.example.exception.ServiceException;
import com.example.exception.TokenMissingException;
import com.example.utils.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @description: token拦截器
 * @author: zeran
 * @date: 2024/12/27 16:15
 */
@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {
	// 保存路径和请求方法的映射
	private static final Map<String, Set<String>> ALLOWED_PATHS = new HashMap<>();

	static {
		// 初始化允许的路径和方法
		ALLOWED_PATHS.put("/merchant/login", Set.of("GET"));
		ALLOWED_PATHS.put("/users/login", Set.of("GET"));
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		// 判断是否匹配允许的路径和方法
		for (Map.Entry<String, Set<String>> entry : ALLOWED_PATHS.entrySet()) {
			String path = entry.getKey();
			Set<String> allowedMethods = entry.getValue();
			if (request.getRequestURI().contains(path) && allowedMethods.contains(request.getMethod())) {
				return true;
			}
		}

		// 从请求头中获取 Token
		String token = request.getHeader("token");
		// 校验 Token 是否存在
		if (token == null || token.isEmpty()) {
			throw new TokenMissingException("token不能为空");
		}
		// 检验token是否过期
		if (!JwtUtil.verifyToken(token)) {
			throw new ServiceException("token无效/已过期");
		}

		return HandlerInterceptor.super.preHandle(request, response, handler);
	}
}
